package com.demo.mapsocial.location;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class MapLocationController {

	private static Context context;
	private LocationManager locationManager;
	private LocationListener locationListener;
	private Location location;
	private LocationUpdateInterface locationUpdate;

	public static final String TAG = "LocationListener";

	public MapLocationController(LocationUpdateInterface locationUpdate) {
		this.locationUpdate = locationUpdate;
		initLocationManager();
	}

	private void initLocationManager() {
		if (locationManager == null) {
			locationManager = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
			
			locationListener = new LocationListener() {

				public void onLocationChanged(Location location) {
					Log.d(TAG, "new location: " + location.getLatitude()
							+ " - " + location.getLongitude());
					locationUpdate.updateLocation(location);
				}

				public void onProviderDisabled(String provider) {
					Log.d(TAG, "onProviderDisabled");
				}

				public void onProviderEnabled(String provider) {
					// TODO Auto-generated method stub

				}

				public void onStatusChanged(String provider, int status,
						Bundle extras) {
					// TODO Auto-generated method stub
				}

			};
			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
		}
	}
	
	public GeoPoint getGeoPoint(Location location) {
		GeoPoint point = null;
		if (location != null) {
			Double latitude = location.getLatitude() * 1E6;
			Double longitude = location.getLongitude() * 1E6;

			point = new GeoPoint(latitude.intValue(), longitude.intValue());
		}

		return point;
	}

	public String getContactLocationAddress(Context context,
			double latitud, double longitude) {
		Geocoder gc = new Geocoder(context, Locale.getDefault());
		List<Address> addresses = new LinkedList<Address>();
		StringBuilder sb = new StringBuilder();

		try {
			addresses = gc.getFromLocation(latitud, longitude, 1);
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (addresses.size() > 0) {
			Address address = addresses.get(0);

			sb.append(address.getAddressLine(0)).append("\n");
			sb.append(address.getLocality()).append(" - ");
			sb.append(address.getCountryCode());
		}

		return sb.toString();
	}

	public void disableLocationManager() {
		if (locationListener != null)
			locationManager.removeUpdates(locationListener);
	}
}
